const xss = require('xss')
const Blog = require('../db/models/Blog')

const getList = async (author, keyword) => {
    const whereOpt = {}
    if (author) {
        whereOpt.author = author
    }
    if (keyword) {
        whereOpt.keyword = new RegExp(keyword)
    }
    const list = await Blog.find(whereOpt).sort({ _id: -1 })

    return list
}

const getDetail = async (id) => {

    const detial = await Blog.findById(id)
    return detial
}

const newBlog = async (blogData = {}) => {
    // blogData 是一个博客对象，包含 title content author 属性
    const title = xss(blogData.title)
    // console.log('title is', title)
    const content = xss(blogData.content)
    const author = blogData.author

    const blog = await Blog.create({
        title,
        content,
        author
    })
    return {
        id: blog._id
    }
}

const updateBlog = async (id, blogData = {}) => {
    // id 就是要更新博客的 id
    // blogData 是一个博客对象，包含 title content 属性

    const title = xss(blogData.title)
    const content = xss(blogData.content)

    const blog = await Blog.findOneAndUpdate({ _id: id }, { title, content }, { new: true })
    if (!blog) {
        return false
    }
    return true

}

const delBlog = async (id, author) => {
    // id 就是要删除博客的 id

    const blog = await Blog.findOneAndDelete({ _id: id }, { author })

    if(!blog){
        return false
    }
    return true;

}

module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog
}